//
//  BasePublicClass.m
//  OvCloudProject
//
//  Created by wmwMAC on 16/10/19.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "BasePublicClass.h"




@implementation BasePublicClass



//不使用代理的提示框
+(void)showPublicUI:(NSString *)describeStr weakself:(UIViewController *)weakself{
    UIAlertController *alertVontroller = [UIAlertController alertControllerWithTitle:@"提示" message:describeStr preferredStyle:UIAlertControllerStyleAlert];
   
    
    // Create the actions.
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        NSLog(@"The \"Okay/Cancel\" alert's cancel action occured.");
        
    }];
    
    // Add the actions.
    [alertVontroller addAction:cancelAction];
    
    
  [weakself presentViewController:alertVontroller animated:YES completion:nil];
    
}

+(void)showPublicUIAndBack:(NSString *)describeStr weakself:(UIViewController *)weakself{
    UIAlertController *alertVontroller = [UIAlertController alertControllerWithTitle:@"提示" message:describeStr preferredStyle:UIAlertControllerStyleAlert];
    
    
    // Create the actions.
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        NSLog(@"The \"Okay/Cancel\" alert's cancel action occured.");
        [weakself.navigationController popViewControllerAnimated: YES];
    }];
    
    // Add the actions.
    [alertVontroller addAction:cancelAction];
    
    
    [weakself presentViewController:alertVontroller animated:YES completion:nil];
    
}



//返回时间差
+ (NSString *)intervalSinceNow: (NSString *) theDate
{
    NSArray *timeArray=[theDate componentsSeparatedByString:@"."];
    theDate=[timeArray objectAtIndex:0];
    
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    [date setDateFormat:@"yyyy-MM-dd"];
    NSDate *d=[date dateFromString:theDate];
    
    NSTimeInterval late=[d timeIntervalSince1970]*1;
    
    
    NSDate* dat = [NSDate date];
    NSTimeInterval now=[dat timeIntervalSince1970]*1;
    NSString *timeString=@"";
    
    NSTimeInterval cha=late-now;
    
    if (cha/3600<1) {//fenzhong
        timeString = [NSString stringWithFormat:@"%f", cha/60];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@", timeString];
        
    }
    if (cha/3600>1&&cha/86400<1) {//小时
        timeString = [NSString stringWithFormat:@"%f", cha/3600];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@", timeString];
    }
    if (cha/86400>1)//天数
    {
        timeString = [NSString stringWithFormat:@"%f", cha/86400];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@", timeString];
        
    }
    return timeString;
}

//随机数生成方法
+(NSInteger)getRandomNumber:(NSInteger)from to:(NSInteger)to
{
    return (NSInteger)(from + (arc4random() % (to - from + 1)));
}


/**
 *  生成一个numcount位的随机数
 *
 *  @param Numcount <#Numcount description#>
 *
 *  @return <#return value description#>
 */
+ (NSString *)returnSuijiNumWithcount:(NSInteger)Numcount from:(NSInteger)startNum To:(NSInteger)endNum{
    
    NSString *Str1 = [NSString stringWithFormat:@"%ld", (startNum + (arc4random() % (endNum - startNum + 1)))];
    for (NSInteger i = 0; i<Numcount-1; i++) {
        Str1 = [Str1 stringByAppendingString:[NSString stringWithFormat:@"%ld", (startNum + (arc4random() % (endNum - startNum + 1)))]];
    }
    NSLog(@"随机shu》》》》%@", Str1);
    return Str1;
    
}

//以逗号分隔
+ (NSString *)returnStringFromDicOrArray:(id)transData{
    NSData *data=[NSJSONSerialization dataWithJSONObject:transData options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\"" withString:@""];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"]" withString:@""];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"[" withString:@""];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    
    NSLog(@"jsonStr==%@",jsonStr);
    return jsonStr;
    
    
    
}
//获取时间戳数据
//获取时间戳
+ (NSString *)getDataString {
    //获取当前时间
    NSDate * today = [NSDate date];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];//格式化
    //    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];获取到秒
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss:SSS"];//获取到毫秒
    NSString * s1 = [df stringFromDate:today];
    NSDate * date = [df dateFromString:s1];
    //转换时间格式
    NSDateFormatter *df2 = [[NSDateFormatter alloc] init];//格式化
    [df2 setDateFormat:@"yyyyMMddHHmmssSSS"];
    [df2 setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    NSLog(@"%@",[df2 stringFromDate:date]);
    return [df2 stringFromDate:date];
}

//获取一个时间点字符串
+(NSString *)getTimeDataPointString{
    //获取当前时间
    
    NSDate * today = [NSDate date];
    
    NSDateFormatter *df = [[NSDateFormatter alloc] init];//格式化
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString * s1 = [df stringFromDate:today];
    return s1;
}

//把json字符串转化成数组或者字典
+(id)parseJSONStringToNSDictionary:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization
                     JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments
                     error:&error];
    if (jsonObject != nil && error == nil){
        NSLog(@"反序列化成功...");
        if ([jsonObject isKindOfClass:[NSDictionary class]]){
            NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
          //  NSLog(@"反序列化后的dictionary数据 = %@", deserializedDictionary);
            return deserializedDictionary;
        }
        else if ([jsonObject isKindOfClass:[NSArray class]]){
            NSArray *deserializedArray = (NSArray *)jsonObject;
           // NSLog(@"反序列化json后的数组 = %@", deserializedArray);
            return deserializedArray;
        }else {
            return nil;
        }
        
    }else{
        NSLog(@"%@", error);
        NSLog(@"反序列化时发生一个错误");
        return nil;
    }
    
}




+(id)parseJsonDataToArrOrdic:(NSData *)tempdata {
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization
                     JSONObjectWithData:tempdata options:NSJSONReadingAllowFragments
                     error:&error];
    if (jsonObject != nil && error == nil){
        NSLog(@"反序列化成功...");
        if ([jsonObject isKindOfClass:[NSDictionary class]]){
            NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
           // NSLog(@"反序列化后的dictionary数据 = %@", deserializedDictionary);
            return deserializedDictionary;
        }
        else if ([jsonObject isKindOfClass:[NSArray class]]){
            NSArray *deserializedArray = (NSArray *)jsonObject;
           // NSLog(@"反序列化json后的数组 = %@", deserializedArray);
            return deserializedArray;
        }else {
            return nil;
        }
        
    }else{
        NSLog(@"%@", error);
        NSLog(@"反序列化时发生一个错误");
        return nil;
    }
}


//判断邮箱
+(BOOL)isValidateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}



//判断手机号码
+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,183,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[0235-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188, 183
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[2378])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186 145
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189  181
     22         */
    NSString * CT = @"^1((33|53|8[019])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
+(BOOL)isChinese:(NSString*)c{
    
    
    for(int i=0; i< [c length];i++){
        int a = [c characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff){
            return NO;
        }
    }
    return YES;
    
}
//颜色
+(UIColor *)returnColorWithR:(NSInteger)Rcolor G:(NSInteger)Gcolor B:(NSInteger)Bcolor alpha:(CGFloat)alpha{
    UIColor *color = [UIColor colorWithRed:Rcolor/255. green:Gcolor/255. blue:Bcolor/255. alpha:alpha];
    return color;
}

//浮点形判断：
+ (BOOL)isPureFloat:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return [scan scanFloat:&val] && [scan isAtEnd];
}
//整形判断
+(BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

//获取当前屏幕显示的viewcontroller
+ (UIViewController *)getCurrentVC{
    
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    //app默认windowLevel是UIWindowLevelNormal，如果不是，找到UIWindowLevelNormal的
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    id  nextResponder = nil;
    UIViewController *appRootVC=window.rootViewController;
    //    如果是present上来的appRootVC.presentedViewController 不为nil
    if (appRootVC.presentedViewController) {
        nextResponder = appRootVC.presentedViewController;
    }else{
        UIView *frontView = [[window subviews] objectAtIndex:0];
        nextResponder = [frontView nextResponder];   ///< style="font-family: Arial, Helvetica, sans-serif;">//  这方法下面有详解    </span>
    }
    
    if ([nextResponder isKindOfClass:[UITabBarController class]]){
        UITabBarController * tabbar = (UITabBarController *)nextResponder;
        UINavigationController * nav = (UINavigationController *)tabbar.viewControllers[tabbar.selectedIndex];
        //        UINavigationController * nav = tabbar.selectedViewController ; 上下两种写法都行
        result=nav.childViewControllers.lastObject;
        
    }else if ([nextResponder isKindOfClass:[UINavigationController class]]){
        UIViewController * nav = (UIViewController *)nextResponder;
        result = nav.childViewControllers.lastObject;
    }else{
        result = nextResponder;
    }
    
    return result;
}

#pragma mark ------ lable自适应长度计算
+ (CGFloat)weidthWithLabelText: (NSString *)text labelHeight: (CGFloat)labelHeight labelFont: (CGFloat)labelFont
{
    //设置label的最大尺寸
    CGSize labelSize = CGSizeMake(kScreen_Width*2/3, labelHeight);
    //字体属性名,字体大小
    NSDictionary *dic = @{NSFontAttributeName :[UIFont systemFontOfSize:labelFont]};
    //设置label的适应尺寸
    CGRect labelBoundingRect = [text boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    return labelBoundingRect.size.width;
}

#pragma mark - 实现确定label高度的方法
+ (CGFloat)heightWithLabelText: (NSString *)text labelWidth: (CGFloat)labelWidth labelFont: (CGFloat)labelFont
{
    //设置label的最大尺寸
    CGSize labelSize = CGSizeMake(labelWidth, 667);
    //字体属性名,字体大小
    NSDictionary *dic = @{NSFontAttributeName :[UIFont systemFontOfSize:labelFont]};
    //设置label的适应尺寸
    CGRect labelBoundingRect = [text boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    return labelBoundingRect.size.height;
}

@end
